package com.iot.inclinometer.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.inclinometer.R;
import com.iot.inclinometer.dao.IBaseInfoDao;
import com.iot.inclinometer.dao.impl.BaseInfoDaoImpl;
import com.iot.inclinometer.pojo.BaseInfo;
import com.iot.inclinometer.util.BaseUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * “新项目”
 * 
 * @author ZSL
 * 
 */
public class NewProUI extends Activity {
	private TextView titleView;		//显示标题(产品型号)
	private ImageView oldProBtn;
	private ImageView paintBtn;
	private ImageView outputBtn;
	private ImageView uploadDBBtn;
	private ImageView configurationBtn;
	private ImageView exitBtn;
	private Button saveBtn;
	private Button startMeasureBtn;
	private Button r_startMeasureBtn;
	/** 工程名 */
	private EditText project_name_edit = null;
	private Spinner projectNameSp = null;
	/** 工点名 */
	private EditText item_name_edit = null;
	private Spinner itemNameSp = null;
	/** 钻孔编号 */
	private EditText drill_num_edit = null; // 钻孔编号
	private Spinner drillNumSp = null;
	
	/** 孔深 */
	private EditText depth_edit = null; // 孔深（单位米）
	/** 里程桩号的第一个组成 */
	private Spinner mark1_spinner = null;
	/** 里程桩号的第二个组成 */
	private EditText mark2_edit = null;
	private EditText mark5_edit = null;//"mark2+mark5"共同构成一部分
	/** 里程桩号的第三个组成 */
	private Spinner mark3_spinner = null;
	/** 里程桩号的第四个组成 */
	private EditText mark4_edit = null;
	/** 位置描述 */
	private EditText loc_edit = null;
	/** X坐标 */
	private EditText x_edit = null;
	/** Y坐标 */
	private EditText y_edit = null;
	/**方位角*/
	private EditText azimuth_edit= null;
	
	private ArrayAdapter<String> projectAdapter = null;

	private ArrayAdapter<String> itemAdapter = null;

	private ArrayAdapter<String> drillAdapter = null;
	
	private InputMethodManager inputMethodManager;       //控制键盘隐藏

	private IBaseInfoDao baseInfoDao = new BaseInfoDaoImpl(this); // 实例化数据库操作对象
	
	private int lightGreen=Color.parseColor("#98FB98");
	private int lightRed=Color.parseColor("#FF3333");

	/** 将孔深传给下一个Activity */
	private String _depth;
	/** 将基本ID传给下一个Activity */
	private int _baseId;
	/** 将工点名称传给下一个Activity */
	private String _itemName;
	/** 将钻孔编号传给下一个Activity */
	private String _drillNum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE); // 取消标题
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_pro_activity);
		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		initView();   	 //初始化控件
		setBtnListener();//设置监听
		initMenu();		 //初始化三级联动菜单
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		titleView=(TextView) findViewById(R.id.tv_top_title); 	//初始化标题
		// -----------初始化button控件start--------------
		oldProBtn = (ImageView) findViewById(R.id.old_pro_btn);
		paintBtn = (ImageView) findViewById(R.id.paint_btn);
		outputBtn = (ImageView) findViewById(R.id.output_btn);
		uploadDBBtn = (ImageView) findViewById(R.id.uploaddbToServer_btn);
		configurationBtn = (ImageView) findViewById(R.id.configuration_btn);
		exitBtn = (ImageView) findViewById(R.id.exit_btn);
		saveBtn = (Button) findViewById(R.id.save_btn); // 保存按钮
		saveBtn.setBackgroundColor(lightGreen);
		startMeasureBtn = (Button) findViewById(R.id.start_measure_btn); // 进入监测按钮
		startMeasureBtn.setEnabled(false);// 设置“进入监听”失效，保存之后才能进入监听
		startMeasureBtn.setBackgroundColor(lightRed);
		r_startMeasureBtn = (Button) findViewById(R.id.r_start_measure_btn); // 进入监测按钮
		r_startMeasureBtn.setEnabled(false);// 设置“进入监听”失效，保存之后才能进入监听
		r_startMeasureBtn.setBackgroundColor(lightRed);
		// -----------初始化button控件end--------------

		// 以下为初始化输入控件
		project_name_edit = (EditText) findViewById(R.id.project_name_edit);
		item_name_edit = (EditText) findViewById(R.id.item_name_edit); // 项目名
		drill_num_edit = (EditText) findViewById(R.id.drill_num_edit); // 钻孔编号
		projectNameSp = (Spinner) findViewById(R.id.project_name_spinner);
		itemNameSp = (Spinner) findViewById(R.id.item_name_spinner);
		drillNumSp = (Spinner) findViewById(R.id.drill_num_spinner);
		depth_edit = (EditText) findViewById(R.id.depth_edit); // 孔深（单位米）
		mark1_spinner = (Spinner) findViewById(R.id.mark1);
		mark2_edit = (EditText) findViewById(R.id.mark2);
		mark5_edit = (EditText) findViewById(R.id.mark5);	//"mark2+mark5"共同构成一部分
		mark3_spinner = (Spinner) findViewById(R.id.mark3);
		mark4_edit = (EditText) findViewById(R.id.mark4);
		loc_edit = (EditText) findViewById(R.id.loc_edit);
		x_edit = (EditText) findViewById(R.id.x_edit);
		y_edit = (EditText) findViewById(R.id.y_edit);
		azimuth_edit = (EditText) findViewById(R.id.azimuth_edit);
	}
	
	
	/**
	 * 初始化三级联动菜单
	 */
	private void initMenu() {
		try {
			initMenu1();
			initMenu2();
			initMenu3();
		} catch (Exception e) {

		}
	}

	private void initMenu1() throws Exception {
		// ---------------------初始化项目名称-start---------------------------
		Set<String> projectNameSet = new HashSet<String>(); // 保存不重复的项目名
		List<String> projectNames = new ArrayList<String>(); // 将Set集合转成List集合,从而放入适配器

		List<BaseInfo> allBaseInfo = this.baseInfoDao.selectBaseInfos();

		for (BaseInfo baseInfo : allBaseInfo) {
			projectNameSet.add(baseInfo.getProjectName());
		}
		for (String projectName : projectNameSet) {
			projectNames.add(projectName);
		}
		Collections.sort(projectNames);//顺序排列
		// 把数组导入到ArrayList中
		projectAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, projectNames);
		projectAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 设置下拉菜单的风格
		projectNameSp.setAdapter(projectAdapter);
		// 绑定适配器
		projectNameSp.setPrompt("请选择项目名");	
	}

	private void initMenu2() throws Exception {
		// **************************初始化二级联动菜单**start****************************
		String selectedProject = projectNameSp.getSelectedItem().toString();
		Set<String> allItemsSet = new HashSet<String>();
		List<String> allItemsList = new ArrayList<String>();

		List<BaseInfo> allItems = this.baseInfoDao
				.selectBaseInfos(selectedProject); // 通过选中的项目名来取得对应的记录，从而得出二级目录的数据
		for (BaseInfo baseInfo : allItems) {
			allItemsSet.add(baseInfo.getItemName());
		}
		for (String item : allItemsSet) {
			allItemsList.add(item);
		}
		Collections.sort(allItemsList);//顺序排列
		// 把数组导入到ArrayList中
		itemAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allItemsList);
		itemAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 设置下拉菜单的风格
		itemNameSp.setAdapter(itemAdapter);
		// 绑定适配器
		itemNameSp.setPrompt("请选择工点名");

		// **************************初始化二级联动菜单**end*************************
	}

	private void initMenu3() throws Exception {
		String selectedProject = projectNameSp.getSelectedItem().toString();
		String selectedItem = itemNameSp.getSelectedItem().toString();
		Set<String> allDrillSet = new HashSet<String>();
		List<String> allDrillList = new ArrayList<String>();

		List<BaseInfo> allDrills = this.baseInfoDao.selectBaseInfos(
				selectedProject, selectedItem);
		for (BaseInfo baseInfo : allDrills) {
			allDrillSet.add(baseInfo.getDrillNum());
		}
		for (String drillNum : allDrillSet) {
			allDrillList.add(drillNum);
		}
		Collections.sort(allDrillList);//顺序排列
		drillAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allDrillList);
		drillAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		drillNumSp.setAdapter(drillAdapter);
		drillNumSp.setPrompt("请选择钻孔编号");
	}
	
	/**
	 * 设置所有按钮的点击监听
	 */
	private void setBtnListener() {
		oldProBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NewProUI.this, OldProUI.class);
				startActivity(intent);
				NewProUI.this.finish();
			}
		});
		paintBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NewProUI.this, PaintProUI.class);
				startActivity(intent);
				NewProUI.this.finish();
			}
		});
		outputBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NewProUI.this, OutputProUI.class);
				startActivity(intent);
				NewProUI.this.finish();
			}
		});
		uploadDBBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NewProUI.this, UploadDBToServerUI.class);
				startActivity(intent);
				NewProUI.this.finish();
			}
		});
		configurationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NewProUI.this, ConfigurationLicenseUI.class);
				startActivity(intent);
			}
		});
		exitBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sureDialog();
			}
		});
		projectNameSp.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					initMenu2();
					initMenu3();
					String selectedProject = projectNameSp.getSelectedItem().toString();
					project_name_edit.setText(selectedProject);	
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}

		});
		itemNameSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					initMenu3();
					String selectedItem = itemNameSp.getSelectedItem().toString();
					item_name_edit.setText(selectedItem);
				} catch (Exception exception) {
					exception.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		drillNumSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					String selectedDrill = drillNumSp.getSelectedItem().toString();		
					drill_num_edit.setText(selectedDrill);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		startMeasureBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(getSharedPreferences("configuration",0).getString("Tclib","").equals(""))
				{
					//参数为空，弹出吐司，提示先设置参数
					Toast.makeText(NewProUI.this, "请设置参数后，再进入监测！",
							Toast.LENGTH_LONG).show();
				}else{	
			    	Intent intent = new Intent();
			    	intent.putExtra("depth", _depth);
			    	intent.putExtra("baseId", _baseId);
			    	intent.putExtra("itemName", _itemName);
			    	intent.putExtra("drillNum", _drillNum);
			    	intent.putExtra("from", "new");
			    	intent.setClass(NewProUI.this, MeasureDataUI.class);
			    	startActivity(intent);
			    	NewProUI.this.finish();
				
				}
			}
		});
		r_startMeasureBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(getSharedPreferences("configuration",0).getString("Tclib","").equals(""))
				{
					//参数为空，弹出吐司，提示先设置参数
					Toast.makeText(NewProUI.this, "请设置参数后，再进入监测！",
							Toast.LENGTH_LONG).show();
				}else{	
			    	Intent intent = new Intent();
			    	intent.putExtra("depth", _depth);
			    	intent.putExtra("baseId", _baseId);
			    	intent.putExtra("itemName", _itemName);
			    	intent.putExtra("drillNum", _drillNum);
			    	intent.putExtra("from", "new");
			    	intent.setClass(NewProUI.this, r_MeasureDataUI.class);
			    	startActivity(intent);
			    	NewProUI.this.finish();
				
				}
			}
		});
		
		// 此处是保存键，获取各个输入框的值，然后存入数据库
		saveBtn.setOnClickListener(saveBtnClickListener);
		
		depth_edit.addTextChangedListener(new TextWatcher() {
			//限制孔深，小数点后最多只能输入一位
				@Override
				public void onTextChanged(CharSequence s, int start, int before,
						int count) {
					if (s.toString().contains(".")) {
						if (s.length() - 1 - s.toString().indexOf(".") > 1) {
							s = s.toString().subSequence(0,
									s.toString().indexOf(".") +2);
							depth_edit.setText(s);
							depth_edit.setSelection(s.length());
						}
					}
					if (s.toString().trim().substring(0).equals(".")) {
						s = "0" + s;
						depth_edit.setText(s);
						depth_edit.setSelection(2);
					}

					if (s.toString().startsWith("0")
							&& s.toString().trim().length() > 1) {
						if (!s.toString().substring(1, 2).equals(".")) {
							depth_edit.setText(s.subSequence(0, 1));
							depth_edit.setSelection(1);
							return;
						}
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
                         
				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					
				}

			});
		x_edit.addTextChangedListener(new TextWatcher() {
			//限制坐标X，小数点后最多只能输入三位
				@Override
				public void onTextChanged(CharSequence s, int start, int before,
						int count) {
					if (s.toString().contains(".")) {
						if (s.length() - 1 - s.toString().indexOf(".") > 3) {
							s = s.toString().subSequence(0,
									s.toString().indexOf(".") + 4);
							x_edit.setText(s);
							x_edit.setSelection(s.length());
						}
					}
					if (s.toString().trim().substring(0).equals(".")) {
						s = "0" + s;
						x_edit.setText(s);
						x_edit.setSelection(2);
					}

					if (s.toString().startsWith("0")
							&& s.toString().trim().length() > 1) {
						if (!s.toString().substring(1, 2).equals(".")) {
							x_edit.setText(s.subSequence(0, 1));
							x_edit.setSelection(1);
							return;
						}
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					
				}

			});
		y_edit.addTextChangedListener(new TextWatcher() {
			//限制坐标Y，小数点后最多只能输入三位
				@Override
				public void onTextChanged(CharSequence s, int start, int before,
						int count) {
					if (s.toString().contains(".")) {
						if (s.length() - 1 - s.toString().indexOf(".") > 3) {
							s = s.toString().subSequence(0,
									s.toString().indexOf(".") + 4);
							y_edit.setText(s);
							y_edit.setSelection(s.length());
						}
					}
					if (s.toString().trim().substring(0).equals(".")) {
						s = "0" + s;
						y_edit.setText(s);
						y_edit.setSelection(2);
					}

					if (s.toString().startsWith("0")
							&& s.toString().trim().length() > 1) {
						if (!s.toString().substring(1, 2).equals(".")) {
							y_edit.setText(s.subSequence(0, 1));
							y_edit.setSelection(1);
							return;
						}
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					
				}
			});	
		azimuth_edit.addTextChangedListener(new TextWatcher() {
			//限制坐标Y，小数点后最多只能输入三位
				@Override
				public void onTextChanged(CharSequence s, int start, int before,
						int count) {
					if (s.toString().contains(".")) {
						if (s.length() - 1 - s.toString().indexOf(".") > 3) {
							s = s.toString().subSequence(0,
									s.toString().indexOf(".") + 4);
							azimuth_edit.setText(s);
							azimuth_edit.setSelection(s.length());
						}
					}
					if (s.toString().trim().substring(0).equals(".")) {
						s = "0" + s;
						azimuth_edit.setText(s);
						azimuth_edit.setSelection(2);
					}

					if (s.toString().startsWith("0")
							&& s.toString().trim().length() > 1) {
						if (!s.toString().substring(1, 2).equals(".")) {
							azimuth_edit.setText(s.subSequence(0, 1));
							azimuth_edit.setSelection(1);
							return;
						}
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					
				}
			});	
		

	}

	private OnClickListener saveBtnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// 取得输入的值
			String projectName = project_name_edit.getText().toString().trim();
			_itemName = item_name_edit.getText().toString().trim();
			_drillNum = drill_num_edit.getText().toString().trim();
			_depth = depth_edit.getText().toString().trim();
			String mark1 = mark1_spinner.getSelectedItem().toString().trim();
			String mark2 = mark2_edit.getText().toString().trim();
			String mark5 = mark5_edit.getText().toString().trim();
			if("".equals(mark2)&&"".equals(mark5)){
				mark2="";
			}else{
				mark2 =mark2+'+'+mark5;
			}
			String mark3 = mark3_spinner.getSelectedItem().toString().trim();
			String mark4 = mark4_edit.getText().toString().trim();			
			String loc = loc_edit.getText().toString().trim();
			String x = x_edit.getText().toString().trim();
			String y = y_edit.getText().toString().trim();
			String azimuth = azimuth_edit.getText().toString().trim();

			BaseInfo baseInfo = new BaseInfo();
			baseInfo.setProjectName(projectName);
			baseInfo.setItemName(_itemName);
			baseInfo.setDrillNum(_drillNum);
			baseInfo.setDepth(_depth);
			baseInfo.setMark1(mark1);
			baseInfo.setMark2(mark2);
			baseInfo.setMark3(mark3);
			baseInfo.setMark4(mark4);
			baseInfo.setLoc(loc);
			baseInfo.setX(x);
			baseInfo.setY(y);
			baseInfo.setAzimuth(azimuth);

			if (BaseUtil.isEmpty(baseInfo, NewProUI.this)) {
				BaseInfo baseInfo2 = baseInfoDao.selectBaseInfos(projectName,_itemName,_drillNum);  
										//根据工程名、工点名、钻孔编号查找有没有已经创建的相同的baseInfo
				if (0 == baseInfo2.getBaseId()) {
					/*
					 * 此处将数据插入数据库中，如果返回true表示插入成功，弹出保存成功，且保存按钮失效，启动“进入监测”按钮
					 * 如果返回的是false，那么弹出提示-->保存失败
					 */
					int flag = baseInfoDao.add(baseInfo);

					if (flag > 0) {
						_baseId = flag;
						// 弹出吐司，表示保存成功
						Toast.makeText(NewProUI.this, "保存成功！",
								Toast.LENGTH_LONG).show();
						saveBtn.setEnabled(false);
						saveBtn.setBackgroundColor(lightRed);
						startMeasureBtn.setEnabled(true); // 保存成功，允许进入监测
						startMeasureBtn.setBackgroundColor(lightGreen);
						r_startMeasureBtn.setEnabled(true); // 保存成功，允许进入监测
						r_startMeasureBtn.setBackgroundColor(lightGreen);
					} else {
						// 弹出吐司，表示保存失败
						Toast.makeText(NewProUI.this, "保存失败，请重新尝试！",
								Toast.LENGTH_LONG).show();
					}
				} else {
					// 弹出吐司，表示保存失败
					Toast.makeText(NewProUI.this, "此工程、工点名称下的钻孔号已存在，请重新命名！",
							Toast.LENGTH_LONG).show();
				}
			}
		}
	};

	/**
	 * 监听返回键
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			sureDialog();
			return true;
		}
		return true;
	}
	
	
	/**
	 * 点击空白处时，隐藏键盘
	 * 
	 *
	 */
	@Override
    public boolean onTouchEvent(MotionEvent event){
        if(event.getAction()==MotionEvent.ACTION_DOWN){
            if(NewProUI.this.getCurrentFocus() != null && NewProUI.this.getCurrentFocus().getWindowToken() != null){
                    inputMethodManager.hideSoftInputFromWindow(NewProUI.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }
	

	/**
	 * 确认框
	 */
	public void sureDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确定退出程序吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

}
